import 'dart:convert';

import 'package:kmxy_base_example/page/page_manage_package.dart';
import 'package:kmxy_base/base/base_package.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:kmxy_base/util/amap_location_util.dart';

abstract class AmapLocationPageState extends BasePageState<AmapLocationPage> {
  final Map<String, Marker> markerMap = <String, Marker>{};
  final Map<String, Polyline> polyLines = <String, Polyline>{};

  AMapWidget? map;
  late AMapController aMapController;

  String locationDataS = '';

  @override
  initData() async {
    AMapLocationUtil.getInstance
        .initLocation('29d5ae3fd1b026b22c6f715ae0baa9fa', '');
    String? latLngListS =
        await SpUtil.getString(AMapLocationUtil.getInstance.SP_LATLNG_LIST);
    // 将坐标添加到坐标列表
    if (latLngListS != null) {
      List patrolLatlngList = jsonDecode(latLngListS);
      for (int i = 0; i < patrolLatlngList.length; i++) {
        AMapLocationUtil()
            .latLngList
            .add(LatLng(patrolLatlngList[i][0], patrolLatlngList[i][1]));
      }
    }
    bool serviceEnabled = await AMapLocationUtil.getInstance.isOpenGps();
    if (!serviceEnabled) {
      loadingShow(status: 'GPS未开启，请开启定位，重新进入');
      return;
    }
    await [
      Permission.location, // 定位
    ].request();
    loadingShow(status: '获取定位中...');
  }

  @override
  destroyData() {
    loadingDismiss();
    AMapLocationUtil.getInstance.stopLocation();
    SpUtil.delKey(AMapLocationUtil.getInstance.SP_LATLNG_LIST);
  }

  initMap() {
    ///使用默认属性创建一个地图
    map = AMapWidget(
      privacyStatement: AMapLocationUtil.getInstance.amapPrivacyStatement,
      apiKey: const AMapApiKey(androidKey: '29d5ae3fd1b026b22c6f715ae0baa9fa'),
      markers: Set<Marker>.of(markerMap.values),
      polylines: Set<Polyline>.of(polyLines.values),
      myLocationStyleOptions: MyLocationStyleOptions(
        true,
        circleFillColor: Colors.transparent,
        circleStrokeColor: Colors.transparent,
        circleStrokeWidth: 1,
        icon: BitmapDescriptor.fromIconPath('assets/img/my_latlng.png'),
      ),
      onMapCreated: onMapCreated,
    );
  }

  /// 地图创建完成的回调
  onMapCreated(AMapController controller) async {
    aMapController = controller;
    AMapLocationUtil.getInstance.setLatLngListener((locationData) async {
      AMapLocationUtil.getInstance.updateMapPosition(
          AMapLocationUtil.getInstance.currentLatLng, controller,
          zoom: 18);
      String gpsAccuracyStatusT = '';
      if (locationData['gpsAccuracyStatus'] == 1) {
        gpsAccuracyStatusT = '强';
      }
      if (locationData['gpsAccuracyStatus'] == 0) {
        gpsAccuracyStatusT = '中';
      }
      if (locationData['gpsAccuracyStatus'] == -1) {
        gpsAccuracyStatusT = '弱';
      }
      setState(() {
        locationDataS =
            '${locationData['locationType']}---${locationData['latitude']},${locationData['longitude']}---${locationData['address']}---GPS信号：$gpsAccuracyStatusT';
      });
    });

    AMapLocationUtil.getInstance.setInitStartLatLngFinishListener(() {
      // 在地图上画出开始点
      Marker marker = AMapLocationUtil.getInstance.addMarker(
          AMapLocationUtil.getInstance.latLngList.first,
          'assets/img/patrol_start.png');
      setState(() {
        markerMap['start'] = marker;
      });
      // 在地图上画出巡查轨迹
      Polyline polyline = AMapLocationUtil.getInstance.addPolyLine(
          AMapLocationUtil.getInstance.latLngList,
          iconPath: 'assets/img/arrowline2.png');
      setState(() {
        polyLines.clear();
        polyLines[polyline.id] = polyline;
      });
    });
    AMapLocationUtil.getInstance.setPatrolListener(() {
      // 在地图上画出巡查轨迹
      Polyline polyline = AMapLocationUtil.getInstance.addPolyLine(
          AMapLocationUtil.getInstance.latLngList,
          iconPath: 'assets/img/arrowline2.png');
      setState(() {
        polyLines.clear();
        polyLines[polyline.id] = polyline;
      });
    });
    AMapLocationUtil.getInstance.startLocation();
  }
}
